import { request } from '../../request/index.js'

Page({
  data: {
    goods_id: '',
    // 示例，如果后端数据没收到就显示这个示例
    goods: {
      imgs: ["https://z3.ax1x.com/2021/05/29/2AYCLj.jpg", "https://z3.ax1x.com/2021/05/29/2AYFwn.jpg", "https://z3.ax1x.com/2021/05/29/2AYVYV.jpg"],
      title: 'test',
      description: '自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新，自用，99新',
      price: '200.00',
      originalPrice: '288.00',
      // tradeMethod: '自提',
      postTime: 1632556746506,//发布的时间戳
      poster: {
        avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/5AdzrOQ4lqG1W72Ph6tnRlibiaHkd0lGlnIF6YxGF5J3IUnZeWMzzSnM2DibMvhkcr6knJGKBlo3n8DYTlL4L5iczQ/132',
        nickName: '上善若水',
        wxNumber: 'sunxiaochuan'
      }
    },
    postTimeTrans: '',
  },
  onLoad(e) {
    // 获取商品 id
    this.setData({
      goods_id: e.scene
      // 调试用
      // goods_id: 1
    })
    // 获取商品详情数据
    // this.getGoodsDetail(this.data.goods_id);
    // 转换时间戳
    // this.setData({
    //   postTimeTrans: this.timestampToTime(this.data.goods.postTime)
    // }),
    this.getGoodsDetail();
  },
  // 获取商品详情数据
  async getGoodsDetail() {
    const result = await request({
      url: '/secondhand/goods/getGood/' + this.data.goods_id
    })
    console.log(result)
    const {imgURLs:imgs,goodName:title,description,price,originalPrice,postTime,user}=result.data.obj;
    this.setData({
      goods: {
        imgs,
        title,
        description,
        price,
        originalPrice,
        postTime,
        poster: {
          avatarUrl: user.imageUrl,
          nickName: user.nickname,
          wxNumber: user.wxNumber
        }
      }
    })
    console.log(result)
  },
  // 收藏
  async star() {
    // 先判断是否已经收藏
    const result = await request({
      url: '/secondhand/goods/isCollected/' + this.data.goods_id
    })
    console.log(result)

    let i = !result.data.obj.star_status
    if (i == true) i = 1;
    else i = 0;
    console.log(i)
    // 若已收藏则取消收藏,反之亦然
    const result2 = await request({
      url: '/secondhand/goods/collected',
      data: {
        goods_id: this.data.goods_id,
        star: i
      }
    })

    console.log(result2)
    if (result.data.obj.star_status == 0) {
      wx.showToast({
        title: '已收藏',
        icon: 'success',
        duration: 1000
      })
    }
    else if (result.data.obj.star_status == 1) {
      wx.showToast({
        title: '已取消收藏',
        icon: 'success',
        duration: 1000
      })
    }
  }
})